import {toJS} from "mobx";
import FormMainView from "../view/Main";
import PreviewHeader from "./Header";
import React, {Fragment} from "react";
import {inject, observer} from "mobx-react";
import {generateSubComponents, propsComToViewCom} from "../component";
import {viewTypes} from "../../../../constants/form";
import "./index.less";
import ThemeContext from "../theme";

const { PC, MOBILE } = viewTypes;
const { Provider } = ThemeContext;

@inject('routing', 'edcFormDesignerStore')
@observer
export default class FormPreview extends React.Component {
  constructor(props) {
    super();
    
    const { componentStore } = props.edcFormDesignerStore;
    const { components = [] } = componentStore;

    this.state = {
      previewType: PC,
      components: this.getComponents(components).map(com => propsComToViewCom(com)),
    };
    this.store = componentStore;
  }

  getComponents(components) {
    const coms = toJS(components);
    const allComs = [];

    coms.forEach(com => {
    	com.name = com.config.title || '';
    	com.config.selected = false;

    	allComs.push(com);

    	// 复合组件 - 需要拆分子组件，便于后台生成多字段用于支持图表分析
    	// 如地址
    	if (com.config.complex) {
    		const subComs = generateSubComponents(com);

    		allComs.push(...subComs);
    	}
    });
    return allComs;
  }

  onPreviewTypeChange = (previewType) => {
    this.setState({ previewType })
  }

  onValueChange = (uuid, value) => {
    const { components } = this.state;
    const com = components.find(com => uuid === com.uuid);

    com.value = value;

    this.setState({
      components
    });
  }

  render() {
    const { previewType, components } = this.state;
    const { formFooter, formHeader } = this.store;
    
    if (!components) return null;
    const {theme} = this.props.edcFormDesignerStore;
    const {background} = theme;
    return (
        <Provider value={theme}>

          <Fragment>

          <PreviewHeader onChange={this.onPreviewTypeChange}/>
            <div className={`wea-edc-fp-wrapper fp_${previewType}`}
              style={background.css}
            >
              <div>
                <div className={`fp_main ${previewType===MOBILE && 'wea-edc-fv-wrapper mobile-device'}`}
                  style={(previewType === PC) && {} || background.css}
                >
                  <FormMainView
                    formHeader={formHeader}
                    formFooter={formFooter}
                    components={components}
                    viewType={previewType}
                    onValueChange={this.onValueChange}
                  />
                </div>
              </div>
            </div>
          </Fragment>
        </Provider>
    );
  }
}